<?php
require('../wp-blog-header.php');
require_once('HTMLPurifier/HTMLPurifier.auto.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

/* Download an image from URL and create attachment obj */
function download_image($post_id,$image_url) {
	try {
		$upload_dir = wp_upload_dir(); // Set upload folder
		$image_data = file_get_contents($image_url); // Get image data
		$filename   = hash('md5',$image_url).'.'.pathinfo($image_url,PATHINFO_EXTENSION); // Create image file name

		// Check folder permission and define file location
		if( wp_mkdir_p( $upload_dir['path'] ) ) {
			$file = $upload_dir['path'] . '/' . $filename;
		} else {
			$file = $upload_dir['basedir'] . '/' . $filename;
		}
		if($image_data!==false) {
			file_put_contents( $file, $image_data ); // Create the image  file on the server
		} else {
			throw new Exception('Cannot fetch image from URL: '.$image_url);
		}
		
	} catch (Exception $e) {
		message('Error downloading image: '.$e->getMessage());
		return;
	}
	
	$wp_filetype = wp_check_filetype( $filename, null ); // Check image file type

	$attachment = array(
		'post_mime_type' => $wp_filetype['type'],
		'post_title'     => sanitize_file_name( $filename ),
		'post_content'   => '',
		'post_status'    => 'inherit'
		);

	$attach_id = wp_insert_attachment( $attachment, $file, $post_id ); // create attachment
	$attach_data = wp_generate_attachment_metadata( $attach_id, $file ); // Define attachment metadata
	wp_update_attachment_metadata( $attach_id, $attach_data ); // Assign metadata to attachment
	// message("--> attachment downloaded: ".wp_get_attachment_url($attach_id));

	return $attach_id;
}


function fetch_images( $post_ID ) {
	$post = get_post($post_ID); // get post
	$image = '';
	// $image_count = 0;
	// get all images from post content
	$image_count = 0;
	// var_dump($matches);
	// message('Match found: '.$image_count);
	if(preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $post->post_content, $matches)){
		// message('Image: '.count($matches[1]));
		$images = $matches[1];
		foreach($images as $image) {
			$image_count++;
			if (strpos($image,$_SERVER['HTTP_HOST'])===false)
			{
				$attach = download_image($post_ID,str_replace(" ","%20",$image));
				$attach_img = wp_get_attachment_url($attach);
				message(' --> '.$attach_img);
				$post->post_content = str_replace($image, $attach_img, $post->post_content);
			}
			
		}
		wp_update_post(array('ID' => $post_ID, 'post_content' => $post->post_content));
	}
	return $image_count;
}

function validateHTML($content) {
	// return $content;
	$config = HTMLPurifier_Config::createDefault();
	// $config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
	$config->set('AutoFormat.AutoParagraph',true);
	$config->set('CSS.AllowedFonts',array());
	$config->set('Output.TidyFormat',true);
	$config->set('CSS.AllowedFonts',array());
	$config->set('HTML.TidyLevel', 'heavy');
	$purifier = new HTMLPurifier($config);
	return $purifier->purify($content);
}

function field($field) {
	if (!isset($_REQUEST[$field]) || trim($_REQUEST[$field])=="") {
		return false;
	}
	return trim($_REQUEST[$field]);
}

function unicode_conv($originalString) {
  // The four \\\\ in the pattern here are necessary to match \u in the original string
  $replacedString = preg_replace("/\\\\u(\w{4})/", "&#$1;", $originalString);
  $unicodeString = mb_convert_encoding($replacedString, 'UTF-8', 'HTML-ENTITIES');
  return $unicodeString;
}

function message($msg,$type="info") {
	if(!field('debug')) return;
	echo $msg."\n"; return;
	if($type=="info") {
		echo "<p style='color:#0064B8;font-family:sans-serif;font-size:12px;margin: 5px 0;'>".$msg."</p>";
	} else if($type=="error") {
		echo "<p style='color:#f00;font-family:sans-serif;font-size:12px;margin: 5px 0;'>".$msg."</p>";
	} else {
		echo "<p style='color:#BE8200;font-family:sans-serif;font-size:12px;margin: 5px 0;'>".$msg."</p>";
	}
}
?>